<?php

namespace addons\cms\controller\api;

use addons\cms\model\Archives as ArchivesModel;
use addons\cms\model\ArchivesInteraction;
use addons\cms\model\ScoreLog;
use addons\qrcode\library\Service;
use addons\third\model\Third;
use app\admin\model\cms\ActivitySign;
use app\common\model\user\Level;
use OSS\OssClient;
use think\Cache;
use think\Db;
use think\Exception;
use think\Response;
use think\Validate;

/**
 * 文档
 */
class Activity extends Base
{
    protected $noNeedLogin = ['index', 'detail', 'get_channel','lists','comment_list'];


    public function index()
    {
        $search = $this->request->request("search", $this->request->request("q", ""));
        $channel = $this->request->request("channel", "");
        $flag = $this->request->param('flag','');
        $search = mb_substr($search, 0, 100);
        $societies_id = (int)$this->request->param('societies_id');
        $pageList = \addons\cms\model\Activity::where('status', 'normal')
            ->field('id,title,title_en,title_zh_cn,image,start_time,end_time,address,address_en,address_zh_cn,attend_num')
            ->where(function ($query) use ($search,$channel,$societies_id,$flag) {
                $keywordArr = explode(' ', $search);
                foreach ($keywordArr as $index => $item) {
                    $query->where('title', 'like', '%' . $item . '%');
                }
                if (!empty($channel)){
                    $query->where('channel_id', $channel);
                }
                if (!empty($societies_id)){
                    $query->where('societies_id', $societies_id);
                }
//                if (!empty($flag)){
//                    $query->where('flag', 'like', '%' . $flag . '%');
//                }
            })
            ->whereNull('deletetime')
            ->order('end_time desc,weigh DESC,createtime DESC')
            ->paginate(10);

        $lang = getHeaderLang();
        if ($pageList) {
            foreach ($pageList as $item) {
                if ($lang!= getDefaultLang()) {
                    $item->title = $item['title_'.$lang];
                    $item->address = $item['address_'.$lang];
                }
                $item->is_sign = 0;
                if ($this->auth->id) {
                    $sign = ActivitySign::where(['user_id'=> $this->auth->id,'activity_id'=>$item->id])->find();
                    $item->is_sign = $sign ? 1 : 0;
                }
                $item->sign_num = ActivitySign::where('activity_id',$item->id)->count();
                $item->sign_remaining = $item->attend_num - $item->sign_num;

                $item->is_finished = 0;
                if ($item->end_time > time()){
                    $item->is_finished = 1;
                }
            }
        }
        $this->success('', $pageList->toArray());
    }

    public function detail()
    {
        $id = $this->request->request("id", "");
        $info = \addons\cms\model\Activity::where('status', 'normal')
            ->where('id',$id)
            ->field('updatetime,deletetime',true)
            ->find();
        if (!$info){
            $this->error('The activity does not exist');
        }
        $lang = getHeaderLang();
        if ($lang!= getDefaultLang()) {
            $info->title = $info['title_'.$lang];
            $info->address = $info['address_'.$lang];
            $info->content = $info['content_'.$lang];
        }
        $is_like = $is_collection = 0;
        if ($this->auth->id){
            if (ArchivesInteraction::where(['user_id'=>$this->auth->id,'aid'=>$info->id,'type' => 'activity'])->find()){
                $is_like = 1;
            }
            if(\addons\cms\model\Collection::where(['user_id' => $this->auth->id,'aid' => $info->id,'type' => 'activity'])->find()){
                $is_collection = 1;
            }
        }
        if ($lang!= getDefaultLang()) {
            $info->title = $info['title_'.$lang];
            $info->content = $info['content_'.$lang];
            $info->address = $info['address_'.$lang];
        }
        $info->is_like = $is_like;
        $info->is_collection = $is_collection;

        $info->is_sign = 0;
        if ($this->auth->id) {
            $sign = ActivitySign::where(['user_id'=> $this->auth->id,'activity_id'=>$info->id])->find();
            $info->is_sign = $sign ? 1 : 0;
        }

        $info->is_finished = 0;
        if ($info->end_time > time()){
            $info->is_finished = 1;
        }
        $config = get_addon_config('cms');
        $score = $config['score']['activity'];
        $info->sign_score = $score;
        $sign_num = ActivitySign::where('activity_id',$info->id)->count();
        $info->attend_num = $sign_num;

        $info->setInc('views',1);
        $this->success('', $info->toArray());

    }

    public function sign(){

        $row = $this->request->post('', '', 'trim,xss_clean');

        $rule = [
            'id|活动ID' => 'require',
            'name|姓名' => 'require',
            'mobile|手机号' => 'require',
            'email|邮箱' => 'require',
            'province|省' => 'require',
            'city|市' => 'require',
            'district|区' => 'require',
        ];
        $msg = [
            'id.require' => 'The campaign ID cannot be empty',
            'name.require' => 'Please fill in your name',
            'mobile.require' => 'Please fill in your mobile phone number',
            'email.require' => 'Please fill in your email address',
            'province.require' => 'Please fill in the province',
            'city.require' => 'Please fill in the city',
            'district.require' => 'Please fill in the district',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($row);
        if (!$result) {
            $this->error($validate->getError());
        }
        $mobile_prefix = $row['mobile_prefix'] ?? 86;
        $mobile = $row['mobile'];
        if ($mobile_prefix == '86'){
            if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
                $this->error('Mobile is incorrect');
            }
        }
        if ($mobile_prefix == '852'){
            if ($mobile && !Validate::regex($mobile, "/^(5[2-9]\d{6}|[6-9]\d{7})$/")) {
                $this->error('Mobile is incorrect');
            }
        }
        $info = \addons\cms\model\Activity::where('status', 'normal')
            ->where('id',$row['id'])
            ->field('updatetime,deletetime',true)
            ->find();
        if (!$info){
            $this->error('The activity does not exist');
        }

        $count = ActivitySign::where(['user_id' => $this->auth->id,'activity_id' => $info->id])->count();
        if ($count > 0){
            $this->error('You have already signed up for the event');
        }

        $total_count = ActivitySign::where('activity_id',$info->id)->count();
        if ($info->attend_num <= $total_count){
            $this->error('The number of participants is full');
        }

        if ($info['end_time'] < time()){
            $this->error('The event has ended');
        }
        $row['user_id'] = $this->auth->id;

        Db::startTrans();
        try {
            $rand = $this->generateRandomString(10);
            $data = [
                'name' => $row['name'],
                'id_card_num' => $row['id_card_num'],
                'mobile' => $row['mobile'],
                'user_address' => $row['user_address'],
                'email' => $row['email'],
                'activity_id' => $row['id'],
                'user_id' => $this->auth->id,
                'createtime' => time(),
                'title' => $info['title'],
                'address' => $info['address'],
                'image' => cdnurl($info['image'],true),
                'verification_code' => $rand,
                'province' => $row['province'],
                'city' => $row['city'],
                'district' => $row['district'],
            ];
            ActivitySign::create($data);
            //增加积分
            $score = ScoreLog::saveLog('activity',$this->auth->id,$row['id']);

            //参加活动次数增加
            $user = \app\common\model\User::where('id',$this->auth->id)->find();

            \app\common\model\User::where('id',$this->auth->id)->update(['sign_activity' => $user->sign_activity + 1]);

            //检测会员是否升级
            Level::UserUpdate($this->auth->id);
            Db::commit();

            $lang = getHeaderLang();
            $field = 'id,pid,name';
            if ($lang != getDefaultLang()){
                $field = 'id,pid,name_'.$lang.' as name';
            }
            $province_info = \app\common\model\cms\Area::where('id',$row['province'])->field($field)->find()['name'];
            $city_info = \app\common\model\cms\Area::where('id',$row['city'])->field($field)->find()['name'];
            $district_info = \app\common\model\cms\Area::where('id',$row['district'])->field($field)->find()['name'];
            $address = $province_info.'-'.$city_info.'-'.$district_info.' '.$row['user_address'];
            $this->success('',['sign_info' => [
                'name' => $row['name'],
                'id_card_num' => $row['id_card_num'],
                'mobile' => $row['mobile'],
                'user_address' => $address,
                'email' => $row['email'],
            ],'activity_info' => [
                'title' => $info['title'],
                'address' => $info['address'],
                'image' => cdnurl($info['image'],true),
                'id' => $row['id'],
                'start_time' => date('Y/m/d H:i',$info['start_time']),
                'end_time' => date('Y/m/d H:i',$info['end_time']),
            ],'score' => $score]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('报名失败');
        }

    }

    function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    public function lists()
    {
        $channel_id = (int)$this->request->param('channel');
        $pagesize = (int)$this->request->param('pagesize',5);

        //加载列表数据
        $pageList = ArchivesModel::alias('a')
            ->where('a.status', 'normal')
            ->field('a.id,a.channel_id,a.user_id,a.title,a.image,a.publishtime,a.createtime,a.description,a.views,a.likes,a.comments,a.dislikes')
            ->whereNull('a.deletetime')
            ->where('channel_id', $channel_id)
            ->paginate($pagesize);

        foreach ($pageList as $item) {
//            if ($item->channel) {
//                $item->channel->visible(explode(',', 'id,parent_id,name,image,diyname,items'));
//            }
            $is_like = $is_collection = 0;
            if ($this->auth->id){
                if (ArchivesInteraction::where(['user_id'=>$this->auth->id,'aid'=>$item->id,'type' => 'like'])->find()){
                    $is_like = 1;
                }
                if(\addons\cms\model\Collection::where(['user_id' => $this->auth->id,'aid' => $item->id,'type' => 'archives'])->find()){
                    $is_collection = 1;
                }
            }
            $item->is_like = $is_like;
            $item->is_collection = $is_collection;
//            if ($item->user) {
//                $item->user->visible(explode(',', 'id,nickname,avatar'));
//            }

            //小程序只显示9张图
//            $item['images_list'] = array_slice(array_filter(explode(',', $item['images'])), 0, 9);

        }
        $this->success('获取成功', $pageList->toArray());
    }

    public function comment_list(){
        $id = $this->request->param('id');
        $info = \addons\cms\model\Activity::where('status', 'normal')
            ->where('id',$id)
            ->field('updatetime,deletetime',true)
            ->find();
        if (!$info){
            $this->error('activity does not exist');
        }
        $list = \addons\cms\model\Comment::with('user')->where('status', 'normal')
            ->where('aid',$id)
            ->field('id,user_id,content,ip_address,createtime')
            ->where('type','activity')
            ->order('createtime desc')
            ->paginate(10);
        $data = $list->toArray();
        $lang = getHeaderLang();

        if ($lang != getDefaultLang()){
            languageTranslation($data,$lang,false,[
                'ip_address','create_date'
            ]);
        }
        $this->success('获取成功',$data);
    }
    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 我的活动
     */
    public function my_sign()
    {
        $type = $this->request->param('type','all');
        $page_model = ActivitySign::where('user_id',$this->auth->id);
        if ($type == 'sign'){
            $page_model->where('verification_status',1);
        }
        if ($type == 'not_sign'){
            $page_model->where('verification_status',0);
        }
        $data = $page_model->order('createtime desc')
            ->whereNull('deletetime')
            ->paginate(10);

        $lang = getHeaderLang();
        foreach ($data as $key => $item) {
            $item->activity_sign_id = 0;
            $info = \addons\cms\model\Activity::where('status', 'normal')
                ->where('id',$item->activity_id)
                ->field('id,title,title_zh_cn,title_en,image,start_time,end_time,address,address_zh_cn,address_en,attend_num')->find();
            if (!$info){
                continue;
            }
            $info->sign_num = ActivitySign::where('activity_id',$info->id)->count();
            $info->verification_status = $item->verification_status;
            $info->sign_remaining = $info->attend_num - $info->sign_num;
            if ($lang!= getDefaultLang()) {
                $info->title = $info['title_'.$lang];
                $info->address = $info['address_'.$lang];
            }
            $info->activity_sign_id = $item->id;
            $data[$key] = $info;
        }

        $this->success('', $data->toArray());

    }


    public function sign_qrcode()
    {
        $config = get_addon_config('qrcode');
        $user_id = $this->auth->id;
        $activity_sign_id = $this->request->param('activity_sign_id');
        if (!$activity_sign_id){
            $this->error('The event registration ID cannot be empty');
        }

        $lang = getHeaderLang();
        $field = 'id,pid,name';
        $activity_field = 'id,title,address,image,start_time,end_time,attend_num';
        if ($lang != getDefaultLang()){
            $field = 'id,pid,name_'.$lang.' as name';
            $activity_field = 'id,title_'.$lang.' as title,address_'.$lang.' as address,image,start_time,end_time,attend_num';
        }
        $activity_sign = ActivitySign::field('title,address,image,updatetime,deletetime',true)->find($activity_sign_id);
        if (!$activity_sign){
            $this->error('Registration for the event does not exist');
        }
        $activity_sign->activity = \addons\cms\model\Activity::where('id',$activity_sign->activity_id)->field($activity_field)->find();
        $activity_sign->activity->start_time_text = date('Y/m/d H:i:s',$activity_sign->activity->start_time);
        $activity_sign->activity->end_time_text = date('Y/m/d H:i:s',$activity_sign->activity->end_time);

        $province_info = \app\common\model\cms\Area::where('id',$activity_sign['province'])->field($field)->find()['name'] ?? '';
        $city_info = \app\common\model\cms\Area::where('id',$activity_sign['city'])->field($field)->find()['name'] ?? '';
        $district_info = \app\common\model\cms\Area::where('id',$activity_sign['district'])->field($field)->find()['name'] ?? '';
        $address = $province_info.'-'.$city_info.'-'.$district_info.' '.$activity_sign['user_address'];

        $activity_sign->user_address = $address;
        $qrcode_path = '';
        if ($activity_sign->verification_status == 0){
            $cache_qrcode = Cache::get('activity_sign_'.$activity_sign_id.'_sign_qrcode');
            if ($cache_qrcode){
                $qrcode_path = $cache_qrcode;
            }else{
                $data = [
                    'code' => $activity_sign->verification_code,
                    'type' => 'activity_sign',
                ];

                $http_build_query_data = http_build_query($data);
                $qrCode = Service::qrcode([
                    'text' => $http_build_query_data
                ]);

                $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';
                $response = Response::create()->header("Content-Type", $mimetype);

                // 直接显示二维码
                header('Content-Type: ' . $qrCode->getContentType());
                $response->content($qrCode->writeString());

                $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
                if (!is_dir($qrcodePath)) {
                    @mkdir($qrcodePath);
                }

                $qrcode_path = '';
                if (is_really_writable($qrcodePath)) {
                    $fileName = md5(implode('', ['text' => $http_build_query_data])). '.'. $config['format'];
                    $aly_oss_config = get_addon_config('alioss');
                    $filePath = $qrcodePath . $fileName;
                    $qrCode->writeFile($filePath);

                    try {
                        $alioss = new OssClient($aly_oss_config['accessKeyId'], $aly_oss_config['accessKeySecret'], $aly_oss_config['endpoint']);
                        $res = $alioss->uploadFile($aly_oss_config['bucket'],$fileName,$filePath);
                        $qrcode_path = $res['info']['url'];
                        Cache::set('activity_sign_'.$activity_sign_id.'_sign_qrcode', $qrcode_path, 0); //缓存300秒(5分钟)
                        Cache::set('activity_sign_qrcode_'.$activity_sign->verification_code, $activity_sign->verification_code, 0); //缓存300秒(5分钟)
                    } catch (\Exception $e) {
                        $this->error($e->getMessage());
                    }
                }
            }
        }
        if ($activity_sign->verification_time){
            $activity_sign->verification_time = date('Y/m/d H:i:s',$activity_sign->verification_time);
        }
        $this->success('', [
            'qrcode' => $qrcode_path ?? '',
//            'code' => $activity_sign->verification_code,
            'sign_detail' => $activity_sign
        ]);
//        $qrcode->setData($member_code);
    }

}
